<script setup>
import FooterNav from "@/components/footerNav.vue";
import {onBeforeMount, ref} from "vue";
import {
  getArticleById,
  getKnowledgeBaseByUserId,
  getUserJoinedKnowledgeBase, saveArticle,
  uploadImage
} from "@/api/request.js";
import {useUserStore} from "@/store/user.js";
import axios from "axios";
import DisplayHTML from "@/components/displayHTML.vue";
import ArticleItem from "@/components/articleItem.vue";

const store = useUserStore()// pinia引用
// 从localStorage中获取缓存的文章
const cacheArticle = ref({
  type: 0,// 0：表示新建；1：表示修改；2表示关联新建
  articleId: 0
})

if (localStorage.getItem('articleId') !== null) {// 判断是否有该元素存在
  cacheArticle.value = JSON.parse(localStorage.getItem('articleId'))
  localStorage.removeItem('articleId')
}


// 编辑中的文章
const article = ref({
  title: '',
  content: '',
  userId: store.userId,
  articleId: 0,
  isPublish: 1
})

const previewArticle = ref(false)// 预览框是否显示
const checked = ref(true)// 文章发布开关


//上传图片并添加到content中
const afterRead = (file) => {
  const formData = new FormData();
  formData.append('file', file.file); // fileInput是<input type="file">元素
  uploadImage(formData).then(response => {
    const fileName = response.data; // 这里获取到上传的文件名
    console.log('File uploaded successfully with name:', fileName);
    article.value.content = article.value.content + `![${file.name}](${axios.getUri()}/${fileName})`
  }).catch(error => {
    console.log(error)
  });
}

const unselectedKnowledgeBases = ref([])
const selectedKnowledgeBases = ref([])
const knowledgeBaseIds = ref([])
const relatedArticle = ref(null)

onBeforeMount(async () => {
  // 获取知识库公共知识库、私有知识库、加入的知识库
  await axios.all([
    // 获取私有知识库
    getKnowledgeBaseByUserId({
      userId: store.userId
    }),
    // 获取公共知识库
    getKnowledgeBaseByUserId({
      userId: 1,
    }),
    // 获取加入的知识库
    getUserJoinedKnowledgeBase({
      userId: store.userId
    })
  ]).then(axios.spread((...res) => {
    if (res[0].data !== null)
      unselectedKnowledgeBases.value.push(...res[0].data)
    if (res[1].data !== null)
      unselectedKnowledgeBases.value.push(...res[1].data)
    if (res[2].data !== null)
      unselectedKnowledgeBases.value.push(...res[2].data)
  })).catch(err => {
    console.log(err)
  })

  if (cacheArticle.value.type !== 0) {
    // 修改
    await getArticleById({
      userId: store.userId,
      articleId: cacheArticle.value.articleId
    }).then(res => {
      if (cacheArticle.value.type === 1) {
        article.value = res.data

        if (article.value.articleId !== 0) {
          getArticleById({
            userId: store.userId,
            articleId: article.value.articleId
          }).then(res => {
            relatedArticle.value = res.data
          })
        }
      } else if (cacheArticle.value.type === 2) {
        article.value = res.data
        relatedArticle.value = res.data
        // 获取关联知识库
      }
    })
  }
})

const clearChoiceOnClick = (knowledgeBase) => {
  // TODO 清除已选择的知识库
  // 将knowledgeBase从selectedKnowledgeBases中移除
  unselectedKnowledgeBases.value.push(knowledgeBase)
  selectedKnowledgeBases.value = selectedKnowledgeBases.value.filter(item => item.id !== knowledgeBase.id)
  knowledgeBaseIds.value = knowledgeBaseIds.value.filter(item => item !== knowledgeBase.id)
}

const selectOnItemClick = (knowledgeBase) => {
  // TODO 选择知识库
  selectedKnowledgeBases.value.push(knowledgeBase)
  unselectedKnowledgeBases.value = unselectedKnowledgeBases.value.filter(item => item.id !== knowledgeBase.id)
  knowledgeBaseIds.value.push(knowledgeBase.id)
}

const saveArticleOnClick = () => {
  if (article.value.title === '') {
    alert('请输入标题')
    return false
  }

  if (article.value.content === '') {
    alert('请输入内容')
    return false
  }

  if (knowledgeBaseIds.value === null || knowledgeBaseIds.value.length === 0) {
    alert('请选择知识库')
    return false
  }

  if (checked.value) {
    article.value.isPublish = 1
  }else {
    article.value.isPublish = 0
  }

  console.log(article.value)

  saveArticle({
    article: article.value,
    knowledgeBaseIds: knowledgeBaseIds.value
  }).then(res => {
    console.log(res)
  }).catch(err => {
    console.log(err)
  })
}
</script>

<template>
  <van-nav-bar title="写作"/>

  <div class="app-container">
    <van-field v-model="article.title" label="标题" placeholder="请输入文章标题"/>

    <div class="markdown-editor">
      <textarea v-model="article.content" class="markdown-input" placeholder="开始编写你的 Markdown..."></textarea>
    </div>

    <!-- 选择知识库 -->
    <div class="select-knowledgeBase">
      <span>选择知识库(至少一个)：</span>
      <!-- 已选择的知识库 -->
      <div class="show-box-selected">
        <span v-if="selectedKnowledgeBases.length === 0" style="color: #999999"><small>未选择知识库</small></span>
        <van-tag v-for="(knowledgeBase, index) in selectedKnowledgeBases" :key="index" :style="{marginRight: '4px'}"
                 plain size="medium" type="primary" @click="clearChoiceOnClick(knowledgeBase)">
          {{ knowledgeBase.name }}
        </van-tag>
      </div>
      <van-divider/>
      <!-- 未选择的知识库 -->
      <div class="show-box-unselected">
        <span v-if="unselectedKnowledgeBases.length === 0" style="color: #999999"><small>已全部被选</small></span>
        <van-tag v-for="(knowledgeBase, index) in unselectedKnowledgeBases" :key="index" :style="{marginRight: '4px'}"
                 color="#999" size="medium" type="primary" @click="selectOnItemClick(knowledgeBase)">
          {{ knowledgeBase.name }}
        </van-tag>
      </div>
    </div>

    <!-- 发布选择器 -->
    <van-cell title="发布">
      <template #right-icon>
        <van-switch v-model="checked" size="16px">
          <template #node>
            <div class="icon-wrapper">
              <van-icon :name="checked ? 'success' : 'cross'" size="12"/>
            </div>
          </template>
        </van-switch>
      </template>
    </van-cell>

    <div class="button-group">
      <van-uploader :after-read="afterRead">
        <van-button type="default">添加图片</van-button>
      </van-uploader>
      <van-button type="default" @click="previewArticle = true">预览</van-button>
      <van-button type="primary" @click="saveArticleOnClick">保存</van-button>
    </div>

    <van-cell v-if="relatedArticle !== null" title="关联文章">
      <template #label>
        <ArticleItem :article="relatedArticle.article" :knowledge-bases="relatedArticle.knowledgeBases" :user="relatedArticle.user"></ArticleItem>
      </template>
    </van-cell>

    <van-popup v-model:show="previewArticle" :style="{ height: '100%', padding: '40px 16px 0'}" close-icon="cross"
               closeable position="top">
      <DisplayHTML :article-content="article.content"></DisplayHTML>
    </van-popup>
  </div>

  <FooterNav/>
</template>

<style lang="less" scoped>
.app-container {
  margin-top: .5rem;
  padding: 0 .5rem;

  & > * {
    margin-bottom: .5rem;
  }
}

.markdown-editor {
  display: flex;
  flex-direction: column;
}

.markdown-input {
  width: 100%;
  height: 35vh;
  font-size: 16px;
  border: 1px solid #ffffff;
  padding: 10px;
  box-sizing: border-box;
}

.select-knowledgeBase {
  width: 100%;
  min-height: 40px;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
  padding: .5rem;
  box-sizing: border-box;

  [class ^= "show-box-"] {
    width: 100%;
    height: 2rem;
    display: flex;
    align-items: center;
    white-space: nowrap;
    overflow-x: auto;
  }

  .van-divider {
    margin: .25rem 0;
  }
}

.button-group {
  width: 100%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 16px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  box-sizing: border-box;
  padding: 1rem;
}

.selected-tags-box {
  width: 100%;
  padding: .5rem;
  background-color: #ffffff;
  display: flex;
  flex-wrap: wrap;
}

.icon-wrapper {
  display: flex;
  width: 100%;
  justify-content: center;
  font-size: 18px;
}

.icon-wrapper .van-icon-success {
  line-height: 18px;
  color: var(--van-blue);
}

.icon-wrapper .van-icon-cross {
  line-height: 18px;
  color: var(--van-gray-5);
}
</style>